<template>
  <div>
    <el-dialog
      class="dialog_modal"
      :title="translate('jcsj')"
      :visible.sync="isOpenSelVideo"
      width="1300px"
    >
      <div>
        <QueryForm
          v-model="filtersSel"
          :query-form-config="queryFormConfigSel"
          @handleQuery="getListSel(1)"
          @clear="clearSel"
        />
        <div class="selList">
          <div v-for="item in videoList" :key="item.id" class="item">
            <el-radio
              v-model="param.videoPath"
              :label="item.videoUrl"
              @change="radioVideoChange"
            >
              <el-image :src="item.gifName" class="spimg" />
              <div class="spbt">
                {{ item.goalType
                }}{{
                  item.goalSore
                    ? "｜" + item.goalSore + translate("fenqiu")
                    : ""
                }}
              </div>
              <div class="sptime">{{ item.goalTime }}</div>
            </el-radio>
          </div>
        </div>
        <Paginations
          :total="videoTotalCount"
          :page="paginationVideo.page"
          @current-change="getListSel"
          @SizeChange="videoPageSizeChange"
        />
      </div>
    </el-dialog>
    <el-drawer
      title="抖音投放计划"
      size="800px"
      :visible.sync="isShowModal"
      @close="closeDrawer"
    >
      <div class="mb20">
        <span class="property-title">发布计划</span>
        <span class="sub-title">支持配置发布至抖音的账号、视频等核心信息</span>
      </div>
      <el-form
        ref="modal"
        :model="param"
        :rules="rules"
        label-suffix="："
        label-width="auto"
      >
        <el-form-item label="计划任务" prop="name">
          <el-input
            v-model="param.name"
            class="w400"
            maxlength="50"
            show-word-limit
            placeholder="请输入计划任务名称"
          />
        </el-form-item>
        <el-form-item label="发布账号">
          <el-radio
            v-model="param.accountFlag"
            :disabled="Boolean(param.id)"
            label="1"
            @change="changeAuth()"
            >全部账号</el-radio
          >
          <el-radio
            v-model="param.accountFlag"
            :disabled="Boolean(param.id)"
            label="0"
            @change="changeAuth('1')"
            >指定账号</el-radio
          >
          <el-button plain @click="handleImpower">新增授权</el-button>
        </el-form-item>
        <el-form-item v-if="param.accountFlag == '0'" prop="publishUser">
          <el-checkbox-group v-model="param.publishUser">
            <el-checkbox
              v-for="item in authAccountList"
              :key="item.userId"
              :disabled="Boolean(param.id)"
              :label="item.userId"
              >{{ item.dyNickName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="视频来源场地">
          <el-radio v-model="param.siteFlag" label="1" @change="changeSite"
            >全部场地</el-radio
          >
          <el-radio v-model="param.siteFlag" label="0" @change="changeSite"
            >指定场地</el-radio
          >
        </el-form-item>
        <el-form-item v-if="param.siteFlag == '0'" prop="siteIds">
          <el-checkbox-group v-model="param.siteIds">
            <el-checkbox
              v-for="item in siteList"
              :key="item.zid"
              :label="item.zid"
              >{{ item.siteName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="视频时间">
          <div class="df_ac" style="height: 36px">
            <el-radio v-model="param.searchTimeType" label="0"
              >当日视频</el-radio
            >
            <el-radio v-model="param.searchTimeType" label="1"
              >指定时间视频</el-radio
            >
            <el-date-picker
              v-if="param.searchTimeType == '1'"
              v-model="param.searchTime"
              type="datetimerange"
              range-separator="-"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :start-placeholder="translate('kssj')"
              :end-placeholder="translate('jssj')"
            />
          </div>
        </el-form-item>
        <el-form-item label="视频封面" prop="videoCover">
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              accept=".jpg,.png"
              :show-file-list="false"
              :on-success="(e) => UploadSuccess(e, 'videoCover')"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-show="param.videoCover"
                class="file"
                :style="'background-image: url(' + param.videoCover + ')'"
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage('videoCover')"
                  />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>封面尺寸建议：720*1280px, 不大于2M。</div>
              <div>(非必传，如果不传封面图，将使用视频封面)</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="视频标题">
          <el-input
            v-model="param.videoTitle"
            class="w400"
            maxlength="50"
            show-word-limit
            placeholder="请输入抖音标题"
          />
        </el-form-item>
        <el-form-item label="热门话题">
          <el-select
            v-model="param.dyVideoTopicTemp"
            multiple
            collapse-tags
            class="w400"
            @change="changeTopic"
          >
            <el-option
              v-for="(item, i) in HotTopicList"
              :key="i"
              :label="item.content"
              :value="item.title"
            />
          </el-select>
          <el-button plain class="ml10" @click="getHotToppic"
            >获取热门话题</el-button
          >
        </el-form-item>
        <el-form-item label="视频话题">
          <el-input
            v-model="param.dyVideoTopic"
            class="w400"
            :autosize="{ minRows: 5, maxRows: 5 }"
            maxlength="400"
            show-word-limit
            type="textarea"
            :placeholder="translate('qsr')"
          />
          <div class="placeholder9">
            多个话题使用#分割,话题请勿包含逗号(,)，如：#话题1#话题2。可选择热门话题
          </div>
        </el-form-item>

        <div class="mb20">
          <span class="property-title">挂载设置</span>
          <span class="sub-title"
            >支持挂载门店地址或者抖音小程序，没有则无需填写</span
          >
        </div>

        <el-form-item label="挂载类型">
          <el-radio v-model="param.mountType" label="0" @change="changeMount"
            >POI门店地址</el-radio
          >
          <el-radio v-model="param.mountType" label="1" @change="changeMount"
            >抖音小程序</el-radio
          >
        </el-form-item>
        <template v-if="param.mountType == '0'">
          <el-form-item label="视频定位">
            <div class="df_ac">
              <dh-area
                :province="param.proName"
                :city="param.cityName"
                :province-code="param.proCode"
                :city-code="param.cityCode"
                :is-show-area="false"
                @change="handleAreaChange($event)"
              />
              <el-input
                v-model="param.searchKey"
                class="w200"
                placeholder="请输入搜索地点"
              />
              <el-button type="primary" @click="queryAdsList"
                >搜索位置</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="门店地址">
            <el-select
              v-model="param.poiId"
              placeholder="请选择视频中挂载的推广门店地址"
              class="w400"
            >
              <el-option
                v-for="item in shopsAddressList"
                :key="item.poiId"
                :label="item.address"
                :value="item.poiId"
              />
            </el-select>
            <div class="placeholder9">地点名称从搜索获取，无需自行添加！</div>
          </el-form-item>
        </template>
        <template v-if="param.mountType == '1'">
          <el-form-item label="小程序标题">
            <el-input
              v-model="param.dyMpTitle"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序标题"
            />
          </el-form-item>
          <el-form-item label="小程序APPID">
            <el-input
              v-model="param.dyMpAppid"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序小程序APPID"
            />
          </el-form-item>
          <el-form-item label="小程序PATH">
            <el-input
              v-model="param.dyMpPath"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序PATH地址，如pages/index/index，选填"
            />
          </el-form-item>
        </template>

        <div class="mb20">
          <span class="property-title">投放规则</span>
          <span class="sub-title">投放时间、投放频次等配置</span>
        </div>

        <el-form-item label="首次投放时间" prop="firstTime">
          <el-date-picker
            v-model="param.firstTime"
            type="datetime"
            :disabled="Boolean(param.lastTime)"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择投放时间"
          />

          <div class="placeholder9">
            设定的时间为首次投放时间，由于视频上传发布等操作非常耗时，发布时间会晚于设定的时间
          </div>
        </el-form-item>
        <el-form-item label="运行频次" prop="intervalTime">
          <span>每 </span>
          <el-input
            v-model="param.intervalTime"
            oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 5)"
            class="w200"
          />
          <span> 小时运行一次，默认为24小时</span>
        </el-form-item>
        <el-form-item label="运行次数" prop="executeNum">
          <span>持续运行 </span>
          <el-input
            v-model="param.executeNum"
            oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 5)"
            class="w200"
          />
          <span> 次后，停止运行；默认运行1次</span>
        </el-form-item>
        <el-form-item>
          <el-button @click="isShowModal = false">{{
            translate("cancel")
          }}</el-button>
          <el-button type="primary" @click="onSubmit">发 布</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  uploadFile,
  launchEditPost,
  DyPublishAccountList,
  DyPublishHotTopic,
  DyPublishGetAdsByStr,

  DyImpower,
  launchDetailPost,
  DyImpowerPage,
  momVideoList,
  momSiteList,
  DyImpowerUploadVideo,
  DyImpowerUploadPhoto
} from '@/api'
import { Loading } from 'element-ui'
import DhArea from '@/components/DhArea'
export default {
  components: {
    DhArea
  },
  data() {
    return {
      param: {
        publishUser: [],
        siteIds: [],
        accountFlag: '1',
        siteFlag: '1',

        searchTimeType: '0'
        // mountType: '0'
      },
      accountList: [],
      authAccountList: [],
      HotTopicList: [],
      shopsAddressList: [],
      siteList: [],

      isShowModal: false,
      isOpenSelVideo: false,
      videoProgress: 0,
      isShowProgress: false,
      filtersSel: {},
      videoList: [],
      videoTotalCount: 0,
      paginationVideo: {
        rows: 10,
        page: 1
      },
      modalDialog: this.$store.state.app.dialog,
      rules: {
        publishUser: [{ required: true, message: '请选择发布账号', trigger: 'change' }],
        siteIds: [{ required: true, message: '请选择指定场地', trigger: 'change' }],
        name: [{ required: true, message: '请输入计划任务', trigger: 'change' }],
        videoPath: [{ required: true, message: '请上传视频', trigger: 'blur' }],
        videoTitle: [{ required: true, message: this.translate('placeInput'), trigger: 'blur' }],
        firstTime: [{ required: true, message: '请输入投放时间', trigger: 'blur' }],
        intervalTime: [{ required: true, message: '请输入运行频次', trigger: 'blur' }],
        executeNum: [{ required: true, message: '请输入运行次数', trigger: 'blur' }]
        // videoCover: [{ required: true, message: '请上传封面', trigger: 'blur' }]
      },
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'DY_MEDIA'
      },
      queryFormConfigSel: {
        formItems: [
          {
            filed: 'siteId',
            type: 'select',
            label: '选择场地',
            labelCode: 'siteName',
            valueCode: 'zid',
            options: []
          },
          {
            filed: 'date',
            type: 'date',
            label: '日期',
            placeholder: '请选择日期'
          },
          {
            filed: 'selTime',
            type: 'timePicker',
            label: '时间段',
            placeholder: '请选择时间段'
          }
        ],
        online: true
      }
    }
  },
  created() {
    this.getAuthList()
  },
  methods: {
    onSubmit() {
      this.$refs['modal'].validate((valid) => {
        if (valid) {
          const param = JSON.parse(JSON.stringify(this.param))
          if (param.searchTimeType === '1') {
            param.searchTimeStart = param.searchTime[0]
            param.searchTimeEnd = param.searchTime[1]
          } else {
            param.searchTimeStart = null
            param.searchTimeEnd = null
          }
          if (param.poiId) {
            const temp = this.shopsAddressList.find(i => i.poiId === param.poiId)
            if (temp && temp.address) {
              param.address = temp.address
            }
          }
          param.publishUser = param.publishUser.join(',')
          param.siteIds = param.siteIds.join(',')
          launchEditPost({ param: { ...param } }).then(res => {
            if (res.errorCode !== '000000') return
            this.$message.success('发布成功')
            this.isShowModal = false
            this.$emit('close')
            this.$emit('success')
          })
        }
      })
    },
    getDetail(id) {
      launchDetailPost({ param: { id } }).then(res => {
        const temp = res.record
        if (!temp.publishUser) {
          temp.accountFlag = '1'
          temp.publishUser = []
        } else {
          temp.accountFlag = '0'
          temp.publishUser = temp.publishUser.split(',')
          DyPublishAccountList({ param: {} }).then(res => {
            this.authAccountList = res.recordList || []
          })
        }
        if (!temp.siteIds) {
          temp.siteFlag = '1'
          temp.siteIds = []
        } else {
          temp.siteFlag = '0'
          temp.siteIds = temp.siteIds.split(',').map(i => Number(i))
        }
        if (temp.searchTimeType === '1') {
          temp.searchTime = [temp.searchTimeStart, temp.searchTimeEnd]
        }
        if (temp.address && temp.poiId) {
          DyPublishGetAdsByStr({
            param: {
              keyword: temp.searchKey || '',
              cityName: temp.cityName
            }
          }).then(res => {
            this.shopsAddressList = res.record.list
          })
        }

        this.param = JSON.parse(JSON.stringify(temp))
      })
    },
    changeMount(val) {
      if (val === '1') {
        this.$set(this.param, 'poiId', '')
      } else {
        this.$set(this.param, 'dyMpTitle', '')
        this.$set(this.param, 'dyMpAppid', '')
        this.$set(this.param, 'dyMpPath', '')
      }
    },
    queryAdsList() {
      if (!this.param.searchKey) {
        return this.$message.warning('请先输入搜索地点')
      }
      DyPublishGetAdsByStr({
        param: {
          keyword: this.param.searchKey || '',
          cityName: this.param.cityName
        }
      }).then(res => {
        this.shopsAddressList = res.record.list
      })
    },
    getAuthList() {
      momSiteList({ param: {} }).then(res => {
        this.siteList = res.recordList || []
      })
    },
    getHotToppic() {
      DyPublishHotTopic({ param: {} }).then(res => {
        if (res.errorCode !== '000000') return
        this.HotTopicList = res.recordList || []
        this.$message.success('获取成功 ')
      })
    },
    closeDrawer() {
      this.isShowModal = false
      this.$emit('close')
    },
    handleOpenSel() {
      this.isOpenSelVideo = true
      this.getSite()
      this.getListSel()
    },
    getListSel(page) {
      const { filtersSel, paginationVideo } = this
      paginationVideo.page = page || paginationVideo.page
      if (filtersSel.selTime && filtersSel.selTime.length > 0) {
        filtersSel.beginTime = filtersSel.selTime[0]
        filtersSel.endTime = filtersSel.selTime[1]
      } else {
        filtersSel.beginTime = null
        filtersSel.endTime = null
      }
      momVideoList({ param: filtersSel, pagination: paginationVideo }).then(res => {
        this.videoList = res.recordList || []
        this.videoTotalCount = res.totalCount
      }, () => {
      })
    },
    getSite() {
      momSiteList({ param: {} }).then(res => {
        this.siteList = res.recordList || []
      })
    },
    videoBefore() {
      this.videoProgress = 0
      this.isShowProgress = true
    },
    changeTopic(e) {
      if (e && e.length > 0) {
        this.$set(this.param, 'dyVideoTopic', '#' + e.join('#'))
      }
    },
    deleteDeviceConfigAddImage(val) {
      this.$set(this.param, val, '')
    },
    videoUploadPro(e, file, files) {
      this.videoProgress = e.percent
      // console.log('videoProgress', e)
      // console.log('e', e)
      // console.log('file', file)
      // console.log('files', files)
    },
    radioVideoChange(v) {
      const loadingInstance = Loading.service({
        target: 'dialog_modal',
        text: '正在上传至抖音服务器......'
      })
      this.isShowProgress = true
      DyImpowerUploadVideo({ param: { userIds: this.param.publishUser.join(','), mediaPath: v } }).then(res => {
        if (res.errorCode !== '000000') return
        this.isShowProgress = false
        this.$set(this.param, 'videoPath', v)
        this.$set(this.param, 'videoData', res.record)
        this.isOpenSelVideo = false
        loadingInstance.close()
      }, () => {
        this.isShowProgress = false
        loadingInstance.close()
      })
    },
    UploadSuccess(e, str) {
      if (str === 'videoPath') {
        DyImpowerUploadVideo({ param: { userIds: this.param.publishUser.join(','), mediaPath: e.showUrl } }).then(res => {
          if (res.errorCode !== '000000') return
          this.isShowProgress = false
          this.$set(this.param, str, e.showUrl)
          this.$set(this.param, 'videoData', res.record)
        }, () => {
          this.isShowProgress = false
        })
      } else {
        DyImpowerUploadPhoto({ param: { userIds: this.param.publishUser.join(','), mediaPath: e.showUrl } }).then(res => {
          if (res.errorCode !== '000000') return
          this.$set(this.param, str, e.showUrl)
          this.$set(this.param, 'videoCoverData', res.record)
        })
      }
    },
    handleImpower() {
      DyImpowerPage({ param: {} }).then(res => {
        if (res.errorCode !== '000000') return
        window.open(res.record, '_blank')
      })
    },
    clearSel() {
      this.filtersSel = {}
      this.getListSel(1)
    },
    handleAreaChange(e) {
      this.$set(this.param, 'proCode', e[0].label)
      this.$set(this.param, 'proName', e[0].value)
      this.$set(this.param, 'cityCode', e[1].label)
      this.$set(this.param, 'cityName', e[1].value)
    },
    videoPageSizeChange(val) {
      this.paginationVideo.rows = val
      this.getListSel()
    },
    changeAuth(val) {
      this.$set(this.param, 'publishUser', [])
      if (val && val === '1') {
        DyPublishAccountList({ param: {} }).then(res => {
          this.authAccountList = res.recordList || []
        })
      }
    },
    changeSite() {
      this.$set(this.param, 'siteIds', [])
    },
    getAccountList() {
      DyImpower({ param: {} }).then(res => {
        this.accountList = res.recordList || []
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.selList {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 200px;
    margin: 20px;
  }
}
.device-uploader {
  width: 80px;
  height: 120px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.device-uploader2 {
  width: 160px;
  height: 110px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
